package com.evo.chat.admin.controller;

import com.evo.chat.admin.domain.AdminUser;
import com.evo.chat.admin.service.AdminUserService;
import com.evo.chat.common.Result;
import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.base.BaseController;
import com.evo.chat.common.exception.ChatException;
import com.evo.chat.common.utils.Md5Util;
import com.evo.chat.common.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @author luwenzheng
 * date 2020-02-05
 */
@RestController
@RequestMapping("/mUser")
@CrossOrigin
public class AdminUserController extends BaseController {

    @Autowired
    AdminUserService service;


    @PostMapping(value = "/create")
    public Result createUser(@RequestParam("name") String name,
                             @RequestParam("password") String password) {
        if(StringUtils.isEmpty(name)){
            throw new ChatException(ResultEnum.USER_NAME_NOT_NULL);
        }
        if(StringUtils.isEmpty(password)){
            throw new ChatException(ResultEnum.USER_PASSWORD_NOT_NULL);
        }
        return service.createUser(name, password);
    }

    @PostMapping(value = "/login")
    public Result login(@RequestParam("name") String name,
                        @RequestParam("password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        loginVerify(name, password);

        AdminUser userInfo = service.login(name, password);

        String token = saveLoginToken(userInfo.getId());

        return ResultUtil.success(token);
    }


}
